package us.impl;

import java.util.List;

import us.IListUs;
import dao.IItemDao;
import dao.IItemListDao;
import dao.IUserDao;
import entities.Item;
import entities.ItemList;
import entities.User;

public class ListUS implements IListUs {

	private IItemListDao itemListDao;

	private IItemDao itemDao;
	private IUserDao userDao;

	public List<ItemList> getAllLists(User user) {
		return userDao.findByExample(user).getAllLists();

	}

	public void addItem(ItemList list, Item item) {
		ItemList listInDB = itemListDao.find(list.getId());
		listInDB.getItems().add(item);

	}

	public void removeItem(ItemList list, int itemId) {
		ItemList listInDB = itemListDao.find(list.getId());
		Item itemToDelete = null;
		for (Item item : listInDB.getItems()) {
			if (item.getId() == itemId) {
				itemToDelete = item;
			}
		}
		listInDB.getItems().remove(itemToDelete);
	}

	public void cleanList(ItemList list) {
		ItemList listInDB = itemListDao.find(list.getId());
		listInDB.getItems().clear();
	}

	public IItemListDao getItemListDao() {
		return itemListDao;
	}

	public void setItemListDao(IItemListDao itemListDao) {
		this.itemListDao = itemListDao;
	}

	public IUserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public ItemList find(int idList) {
		List<ItemList> allList = itemListDao.findAll();
		if (allList != null) {

			for (ItemList list : allList) {
				if (list.getId() == idList) {
					return list;
				}
			}
		}
		return null;
	}

	@Override
	public void addList(User user, ItemList list) {
		User userInDB = userDao.find(user.getLogin());
		if (userInDB != null) {
			userInDB.getAllLists().add(list);
		}

	}

	@Override
	public void removeList(User user, ItemList list) {
		User userInDB = userDao.find(user.getLogin());
		if (userInDB != null) {
			ItemList listToRemove = null;

			for (ItemList l : userInDB.getAllLists()) {
				if ((int)l.getId() == list.getId()) {
					listToRemove = l;
				}
			}
			itemListDao.remove(listToRemove);
			userInDB.getAllLists().remove(listToRemove);
			
		}

	}

	@Override
	public void checkItem(int itemId) {
		Item item = itemDao.find(itemId);
		item.setChecked(!item.isChecked());
		
	}

	public IItemDao getItemDao() {
		return itemDao;
	}

	public void setItemDao(IItemDao itemDao) {
		this.itemDao = itemDao;
	}

}